#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QCoreApplication>
#include <QTcpSocket>
#include <QJsonObject>
#include <QJsonDocument>
#include <QDebug>
#include <QMenuBar>
#include <QToolBar>
#include <QFileDialog>
#include <QDesktopServices>
#include "protocol.h"
#include "tools.h"


enum{
    VEHICLEPAGE = 1,
    PARKINGSPOTPAGE,
    PARKINGRECORDPAGE,
    PAYMENT,
    STATISTICSPAGE,
};

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
    , retryCount(0)
{
    ui->setupUi(this);
    this->setWindowTitle("Park+智慧停车系统");
    QIcon icon(":/Icon.png");
    this->setWindowIcon(icon);
    this->setGeometry(0,0,1081,719);

    // 状态栏显示
    QStatusBar *stbar = statusBar();
    setStatusBar(stbar);
    label = new QLabel("正在连接服务器...", this);
    stbar->addWidget(label);


    // 初始化 socket
    socket = new QTcpSocket(this);
    socket->connectToHost("47.98.42.43", 8889);

    // 成功连接
    connect(socket, &QTcpSocket::connected, this, [this]() {
        qDebug() << "成功连接到服务器!";
        label->setText("已经连接服务器");
        reconnectTimer->stop();  // 停止重连
    });

    //菜单栏
    QMenuBar* menuBar = this->menuBar();
    QMenu* menu1 = new QMenu("文件(&F)");
    QMenu* menu2 = new QMenu("操作(&E)");
    QMenu* menu3 = new QMenu("关于(&H)");
    QMenu* menu4 = new QMenu("AI(&A)");
    menuBar->addMenu(menu1);
    menuBar->addMenu(menu2);
    menuBar->addMenu(menu3);
    menuBar->addMenu(menu4);
    QAction* act0 = new QAction("收费方案(&P)");
    menu3->addAction(act0);
    connect(act0,&QAction::triggered,this,&MainWindow::showPaymentPlan);
    QAction* actAI = new QAction("DeepSeak(&D)");
    menu4->addAction(actAI);
    connect(actAI,&QAction::triggered,this,&MainWindow::onHandleAI);

    QAction* act6 =new QAction("打开停车记录本地缓存文件(&L)");
    QAction* act7 =new QAction("打开缴费记录本地缓存文件(&P)");

    menu1->addAction(act6);
    menu1->addAction(act7);
    connect(act6,&QAction::triggered,this,&MainWindow::openLocalParkingRecordFile);
    connect(act7,&QAction::triggered,this,&MainWindow::openLocalPaymentFile);


    //工具栏
    QToolBar* toolBar = new QToolBar("功能");
    this->addToolBar(Qt::LeftToolBarArea,toolBar);
    QAction* act1 = new QAction("出入车辆管理(&I)");
    QAction* act2 = new QAction("车位查询(&S)");
    QAction* act3 = new QAction("停车记录(&R)");
    QAction* act4 = new QAction("缴费记录(&F)");
    QAction* act5 = new QAction("统计(&T)");
    toolBar->addAction(act1);
    toolBar->addAction(act2);
    toolBar->addAction(act3);
    toolBar->addAction(act4);
    toolBar->addAction(act5);

    menu2->addAction(act1);
    menu2->addAction(act2);
    menu2->addAction(act3);
    menu2->addAction(act4);
    menu2->addAction(act5);

    VehiclePage* vehiclePage = new VehiclePage(this,socket);
    ParkingSpotPage* parkingspotPage = new ParkingSpotPage(this,socket);
    ParkingRecord* parkingRecordPage = new ParkingRecord(this,socket);
    PaymentPage* paymentPage = new PaymentPage(this,socket);
    StatisticsPage* statisticsPage = new StatisticsPage(this,socket);

    // 初始化 stackedWidget
    stackedWidget = new QStackedWidget(this);
    this->setCentralWidget(stackedWidget);

    stackedWidget->addWidget(vehiclePage);// index 0
    stackedWidget->addWidget(parkingspotPage); // index 1
    stackedWidget->addWidget(parkingRecordPage); // index 2
    stackedWidget->addWidget(paymentPage); // index 3
    stackedWidget->addWidget(statisticsPage); // index 4

    // 连接工具栏
    connect(act1, &QAction::triggered, this, &MainWindow::showVehiclePage);
    connect(act2, &QAction::triggered, this, &MainWindow::showQueryPage);
    connect(act3, &QAction::triggered, this, &MainWindow::showRecordPage);
    connect(act4, &QAction::triggered, this, &MainWindow::showPaymentPage);
    connect(act5, &QAction::triggered, this, &MainWindow::showStatisticsPage);


    // 初始化重连定时器
    reconnectTimer = new QTimer(this);
    reconnectTimer->setInterval(3000); // 每隔3秒尝试重连
    reconnectTimer->setSingleShot(false);

    connect(reconnectTimer, &QTimer::timeout, this, [this]() {
        if (retryCount <= 0) {
            reconnectTimer->stop();
            label->setText("重连失败，请检查网络。");
            return;
        }
        label->setText("服务器失去连接...正在重连（剩余 " + QString::number(retryCount) + " 次）");
        qDebug() << "尝试重新连接服务器，剩余次数：" << retryCount;
        retryCount--;

        socket->abort(); // 断开当前连接（如果有）
        socket->connectToHost("47.98.42.43", 8889);
    });

    // 断开连接时启动重连
    connect(socket, &QTcpSocket::disconnected, this, [this]() {
        retryCount = 10;
        reconnectTimer->start();
        label->setText("服务器失去连接，准备重连...");
    });


    connect(socket, &QTcpSocket::readyRead, this, &MainWindow::onSocketReadyRead);// 读取服务器消息
    connect(this, &MainWindow::messageForVehiclePage, vehiclePage, &VehiclePage::handleServerMessage);
    connect(this, &MainWindow::messageForParkingSpotPage, parkingspotPage, &ParkingSpotPage::handleServerMessage);
    connect(this,&MainWindow::messageForParkingRecordPage,parkingRecordPage,&ParkingRecord::handleServerMessage);
    connect(this,&MainWindow::messageForPaymentPage,paymentPage,&PaymentPage::handleServerMessage);
    connect(this,&MainWindow::messageForStatisticsPage,statisticsPage,&StatisticsPage::handleServerMessage);
    // 初始连接失败时弹窗提示
    bool r = socket->waitForConnected();
    if (!r)
    {
        QMessageBox::critical(this, "连接失败", socket->errorString());
        exit(1);
    }
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::reconnect()
{
    connect(socket, &QTcpSocket::connected, this, [this](){
        qDebug() << "成功连接到服务器!";
        label->setText("已经连接服务器");
    });
}


void MainWindow::on_pushButton_clicked()
{
    //获取到输入框的内容
    const QString& text = ui->lineEdit->text();

    // 创建JSON对象
    QJsonObject root;
    root["func"] = "1";
    root["message"] = text;

    // 将JSON对象转换为文档
    QJsonDocument doc(root);
    //将json格式的内容发给服务器了
    socket->write(doc.toJson());

    //发送给服务器
    //socket->write(text.toUtf8());

    //把发出的消息显示到界面上
    ui->listWidget->addItem("客户端:功能1+"+text);
    ui->lineEdit->setText("");
}



void MainWindow::on_pushButton_2_clicked()
{
    const QString& text = ui->lineEdit->text();
    // 创建JSON对象
    QJsonObject root;
    root["func"] = "2";
    root["message"] = text;

    // 将JSON对象转换为文档
    QJsonDocument doc(root);
    //将json格式的内容发给服务器了
    socket->write(doc.toJson());

    //把发出的消息显示到界面上
    ui->listWidget->addItem("客户端:功能2+"+text);
    ui->lineEdit->setText("");

}

void MainWindow::onSocketReadyRead()
{
    QByteArray data = socket->readAll();
    qDebug()<<"MainWindow::onSocketReadyRead(),get data: "<<data;
    QJsonObject json;
    QJsonObject message;
    Decode(data, json);
    qDebug()<<"MainWindow::onSocketReadyRead(),after decode:"<<json;
    int func = json.value("func").toInt();
    message = json.value("message").toObject();
    qDebug() << "MainWindow收到消息，func=" << func<<"message:"<<message;

    switch (func)
    {
        case VEHICLEPAGE:
            emit messageForVehiclePage(message);
            break;
        case PARKINGSPOTPAGE:
            emit messageForParkingSpotPage(message);
            break;
        case PARKINGRECORDPAGE:
            emit messageForParkingRecordPage(message);
            break;
        case PAYMENT:
            emit messageForPaymentPage(message);
            break;
        case STATISTICSPAGE:
        emit messageForStatisticsPage(message);
        break;
    default:
        qDebug() << "未处理的 func：" << func;
        break;
 }
}

void MainWindow::showVehiclePage() {
    stackedWidget->setCurrentIndex(0);
}
int i = 1;
void MainWindow::showQueryPage() {
    stackedWidget->setCurrentIndex(1);
if(i==1)
{
    QJsonObject root;
    QJsonObject message;
    root["func"] = 7;

    message["signal"] = 1;
    root["message"] = message;
    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
    i++;
}


}
int j = 1;
void MainWindow::showRecordPage() {
stackedWidget->setCurrentIndex(2);
//if(j==1)
//{
    int incompleteRows = countIncompleteLines("parking_record.txt");
    int lines = countLinesInFile("parking_record.txt")-1;
    qDebug() << "不完整行数为:" << incompleteRows;
    qDebug() << "总行数:" << lines;
    int n = lines-incompleteRows;
    QJsonObject root;
    QJsonObject message1;
    QJsonObject message2;
    root["func"] = 9;
    //message["signal"] = 1;
    message2["message2"] = message1;
    message2["n"] = n;
    message2["total"]= lines;
    root["message"] = message2;

    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
    //j++;
//}
}

void MainWindow::showPaymentPage() {
    stackedWidget->setCurrentIndex(3);
    int lines = countLinesInFile("payment_records.txt")-1;
    QJsonObject root;
    QJsonObject message1;
    QJsonObject message2;
    root["func"] = 10;
    //message["signal"] = 1;
    message2["message2"] = message1;
    message2["lines"] = lines;
    root["message"] = message2;

    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
}

void MainWindow::showStatisticsPage() {
    stackedWidget->setCurrentIndex(4);

    QJsonObject root;
    QJsonObject message;
    root["func"] = 11;
    //message["signal"] = 1;
    root["message"] = message;
    QByteArray dataToSend = Encode(root);
    socket->write(dataToSend);
}

void MainWindow::showPaymentPlan()
{
      QDialog* dialog = new QDialog(this);
      dialog->setWindowTitle("收费方案");

      QVBoxLayout* layout = new QVBoxLayout(dialog);
      QLabel* label1 = new QLabel("起步价(前30分钟):3元\n每增加30分钟:2元\n全天封顶:20元", dialog);
      QLabel* label2 = new QLabel("说明：不足30分钟按30分钟计费。", dialog);
      layout->addWidget(label1);
      layout->addWidget(label2);

      QPushButton* okButton = new QPushButton("我知道了", dialog);
      layout->addWidget(okButton);
      connect(okButton, &QPushButton::clicked, dialog, &QDialog::accept);

      dialog->setLayout(layout);
      dialog->exec();  // 模态显示
}

void MainWindow::onHandleAI()
{
    //if (aiDialog==nullptr) {
        aiDialog = new AIChatDialog(); // 首次点击时创建对话框
    //}
    aiDialog->show();  // 显示对话框
    aiDialog->activateWindow(); // 激活窗口（如果已存在）
}

void MainWindow::openLocalPaymentFile()
{
    QString filePath = "payment_records.txt";
    if (QFile::exists(filePath)) {
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    } else {
        qWarning() << "文件不存在：" << filePath;
    }
}

void MainWindow::openLocalParkingRecordFile()
{
    QString filePath = "parking_record.txt";
    if (QFile::exists(filePath)) {
        QDesktopServices::openUrl(QUrl::fromLocalFile(filePath));
    } else {
        qWarning() << "文件不存在：" << filePath;
    }
}











